package cn.techjc;

import java.io.*;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chenyu on 2016/4/26.
 */
public class FileUtil {

    private static final String htmlPath = "C:\\Users\\chenyu\\Desktop\\Evernote.enex_files";
    private static final String imagePath = htmlPath+File.separator+"image";


    public static void bytes2file(byte[] bytes,String fileFullName) throws IOException {
        File file = new File(htmlPath+File.separator+fileFullName);
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            bufferedOutputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        }
    }

    public static void string2file(String str,String fileFullName) throws IOException {
        File file = new File(imagePath+File.separator+fileFullName);
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            bufferedWriter.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bufferedWriter.flush();
            bufferedWriter.close();
        }
    }


    public static List<String> pattern (String reg, String source){

        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(source);
        List<String> list = new ArrayList<String>();
        while (matcher.find()){
            list.add(matcher.group());
        }
        return list;
    }

    public static String patternOne (String reg,String source){
        List<String> list =  pattern(reg,source);
//        System.out.println(list);
        if(list.size()>0){
            return list.get(0);
        }
        return "";
    }

    public final static String MD5(byte[] btInput) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
